import { NextRequest, NextResponse } from 'next/server';
import { readCategories, writeCategories } from '@/lib/data';
import { verifyToken } from '@/lib/auth';

export async function POST(request: NextRequest) {
  try {
    const token = request.cookies.get('token')?.value;
    const decoded = verifyToken(token || '');

    if (!decoded || !decoded.isAdmin) {
      return NextResponse.json(
        { success: false, message: '需要管理员权限' },
        { status: 403 }
      );
    }

    const { ids } = await request.json();
    if (!Array.isArray(ids) || ids.length === 0) {
      return NextResponse.json(
        { success: false, message: '缺少要删除的分类ID' },
        { status: 400 }
      );
    }

    const categories = readCategories();
    const idSet = new Set<string>(ids);

    // 只删除没有子分类的 ID，其余作为 skipped 返回
    const hasChildren = (id: string) => categories.some(c => c.parentId === id);
    const deletable = ids.filter((id: string) => !hasChildren(id));
    const skipped = ids.filter((id: string) => hasChildren(id));

    const after = categories.filter(c => !deletable.includes(c.id));
    writeCategories(after);

    return NextResponse.json({ success: true, deleted: deletable.length, skipped });
  } catch (error) {
    return NextResponse.json(
      { success: false, message: '批量删除分类失败' },
      { status: 500 }
    );
  }
}


